
package filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class AuthorizationFilter implements Filter{

    private FilterConfig filterConfig;
    private String errorPage;

    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
           errorPage = filterConfig.getInitParameter("error_page"); 
       }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpSession session = ((HttpServletRequest)request).getSession(true);
        String logged = (String)session.getAttribute("logged");
        String admin = (String)session.getAttribute("admin");
        if(logged != null && admin != null){
            chain.doFilter(request, response);
            return;            
        }
        //si no es admin, redirigir a errorPage        
        filterConfig.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
            return;
    }
    
    public void destroy(){
    }
}